package com.mentalhealthplatform.global.rbac.security;

/*
@Component
public class DynamicPermissionFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(DynamicPermissionFilter.class);
    private final PermissionService permissionService;

    public DynamicPermissionFilter(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 获取请求的路径和方法（用于日志）
        String requestEndpointPath = request.getRequestURI();
        String requestMethod = request.getMethod();
        logger.debug("Request received: Path [{}] Method [{}]", requestEndpointPath, requestMethod);

        if (true){
            filterChain.doFilter(request, response);
            logger.info("Continue......");
            return;
        }


        // 从请求属性中获取 CustomSecurityContext 中的 Endpoint
        CustomSecurityContext customSecurityContext = (CustomSecurityContext) request.getAttribute("customSecurityContext");
        Endpoint endpoint = customSecurityContext != null ? customSecurityContext.getEndpoint() : null;

        if (endpoint == null) {
            logger.warn("No endpoint found for Path [{}] Method [{}]", requestMethod, requestEndpointPath);

            //测试时可以继续
            filterChain.doFilter(request, response);
            return;
        }

        logger.debug("Found endpoint: [{}] with allowAnonymous: [{}]", endpoint.getPath(), endpoint.isAllowAnonymous());

        // 检查 Endpoint 的 accessLevel
        AccessLevel accessLevel = endpoint.getAccessLevel();
        logger.debug("Endpoint [{}] has access level: [{}]", endpoint.getPath(), accessLevel);

        // 根据不同的 accessLevel 执行不同的逻辑
        switch (accessLevel) {
            case PUBLIC:
                logger.info("Access granted: Endpoint [{}] is public", endpoint.getPath());
                filterChain.doFilter(request, response);
                return;

            case PRIVATE:
                handlePrivateAccess(request, response, filterChain, endpoint);
                return;

            case PROTECTED:
                handleProtectedAccess(request, response, filterChain, endpoint);
                return;

            default:
                logger.warn("Access Denied: Unknown access level for endpoint [{}]", endpoint.getPath());
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                return;
        }
    }

    // 处理 PRIVATE 访问级别
    private void handlePrivateAccess(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Endpoint endpoint)
            throws IOException, ServletException {
        // 获取当前的用户认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();

            if (principal instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) principal;

                // 使用 Endpoint 直接查找相关的权限
                List<Permission> permissions = permissionService.findPermissionsByEndpoint(endpoint);

                if (permissions.size() != 1) {
                    logger.warn("Access Denied: Endpoint [{}] should have exactly one permission for PRIVATE access", endpoint.getPath());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                    return;
                }

                Permission requiredPermission = permissions.get(0);
                boolean hasPermission = userDetails.getAuthorities().stream()
                        .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(requiredPermission.getPermissionName()));

                if (hasPermission) {
                    logger.info("Access granted: User [{}] has permission [{}] for PRIVATE endpoint [{}]", userDetails.getUsername(), requiredPermission.getPermissionName(), endpoint.getPath());
                    filterChain.doFilter(request, response);
                } else {
                    logger.warn("Access Denied: User [{}] does not have permission [{}] for PRIVATE endpoint [{}]", userDetails.getUsername(), requiredPermission.getPermissionName(), endpoint.getPath());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                }
            }
        } else {
            logger.warn("Access Denied: Unauthenticated access attempt to PRIVATE endpoint [{}]", endpoint.getPath());
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
        }
    }

    // 处理 PROTECTED 访问级别
    private void handleProtectedAccess(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, Endpoint endpoint)
            throws IOException, ServletException {
        // 获取当前的用户认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();

            if (principal instanceof UserDetails) {
                UserDetails userDetails = (UserDetails) principal;

                // 使用 Endpoint 直接查找相关的权限
                List<Permission> permissions = permissionService.findPermissionsByEndpoint(endpoint);

                if (permissions.isEmpty()) {
                    logger.warn("Access Denied: No permissions found for PROTECTED endpoint [{}]", endpoint.getPath());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                    return;
                }

                // 遍历找到的权限列表，检查是否有匹配的权限
                boolean hasPermission = permissions.stream()
                        .anyMatch(requiredPermission ->
                                userDetails.getAuthorities().stream()
                                        .anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals(requiredPermission.getPermissionName()))
                        );

                if (hasPermission) {
                    logger.info("Access granted: User [{}] has permission for PROTECTED endpoint [{}]", userDetails.getUsername(), endpoint.getPath());
                    filterChain.doFilter(request, response);
                } else {
                    logger.warn("Access Denied: User [{}] does not have permission for PROTECTED endpoint [{}]", userDetails.getUsername(), endpoint.getPath());
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
                }
            }
        } else {
            logger.warn("Access Denied: Unauthenticated access attempt to PROTECTED endpoint [{}]", endpoint.getPath());
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
        }
    }

}
 */